<template>
  <div class="a3-page">
    <div class="tool-view">
      <div class="tool-l">
        <span>时间刻度</span>
        <select
          class="select"
          v-model="params.type"
          style="transform: scale(0.9); width: 5rem"
        >
          <option v-for="item in options" :key="item.value" :value="item.value">
            {{ item.label }}
          </option>
        </select>
        <!-- <n-select
          placeholder="选择时间刻度"
          style="transform: scale(0.9); width: 5rem"
          v-model:value="params.type"
          :options="options"
          size="small"
        /> -->
        <span>时间筛选</span>
        <div class="pcker-view">
          <div class="mask" @click="show = true"></div>
          <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
            <n-date-picker
              style="transform: scale(0.9)"
              v-model:value="range"
              :type="pickerType"
              :show="show"
              clearable
              :to="false"
              size="small"
              @update:formatted-value="timeChange"
              :is-date-disabled="disablePreviousDate"
              @confirm="show = false"
              @blur="show = false"
            />
          </n-config-provider>
        </div>
        <n-button class="btn" type="success" @click="GetProduceInfomationFun">
          查询
        </n-button>
      </div>
    </div>
    <div ref="container" class="table-view">
      <n-data-table
        :style="{
          transform: 'scale(0.6)',
          'transform-origin': 'top left',
          width: tableW,
        }"
        remote
        :loading="loading"
        :data="data"
        :columns="columns"
        :single-line="false"
        :pagination="false"
        :scroll-x="scrollX"
        virtual-scroll
        @update:page="handlePageChange"
        :max-height="height"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { zhCN, dateZhCN } from "naive-ui";
import { useRoute } from "vue-router";
import { GetProduceInfomation } from "@/server";
import { today } from "@/tools/radom";
import { useAppStore } from "@/store/modules/user";
const store = useAppStore();
const data = ref([]) as any;
const columns = ref([]) as any;
const loading = ref(false);
const tableW = ref("100%");
const route = useRoute();
const modelId = computed(() => route.params.id);
const pagination = ref({
  page: 1,
  pageCount: 1,
  pageSize: 20,
  pageSlot: 7,
});
const range = ref<[number, number]>([Date.now(), Date.now()]);
const options = [
  {
    label: "天",
    value: "天",
  },
  {
    label: "月",
    value: "月",
  },
  {
    label: "年",
    value: "年",
  },
];
const show = ref(false);
const scrollX = ref(1400);
const pickerType = computed(() => {
  if (params.value.type === "天") {
    return "daterange";
  } else if (params.value.type === "月") {
    return "monthrange";
  } else {
    return "yearrange";
  }
});
const params = ref({
  type: "天",
  startTime: today(),
  endTime: today(),
}) as any;
const timeChange = (e: any) => {
  params.value.startTime = e[0];
  params.value.endTime = e[1];
};
const handlePageChange = (curent: number) => {
  console.log(curent);
  pagination.value.page = curent;
  GetProduceInfomationFun();
};
watch(
  () => modelId.value,
  () => {
    GetProduceInfomationFun();
  }
);
const lock = ref(false);
const unLock = () => {
  setTimeout(() => {
    lock.value = false;
  }, 1000);
};
//获取初始化数据
const GetProduceInfomationFun = async () => {
  loading.value = true;
  if (lock.value) {
    return false;
  }
  lock.value = true;
  const res: any = await GetProduceInfomation(params.value);
  if (res.result.isSuccess) {
    loading.value = false;
    unLock();
    createData(res.result.result);
  } else {
    unLock();
    loading.value = false;
    store.error(res.result.message); // 错误提示
  }
};
GetProduceInfomationFun();
const container = ref(null) as any;
const height = ref(0);
const updateHeight = () => {
  const containerHeight = container.value.offsetHeight;
  console.log("Container Height:", containerHeight);
  height.value = containerHeight + containerHeight * 0.32;
};
const disablePreviousDate = (ts: number) => {
  return ts > Date.now();
};
onMounted(() => {
  // 获取页面宽度
  const pageWidth = window.innerWidth;

  // 计算百分比
  const percentage = (pageWidth / (pageWidth * 0.6)) * 100;
  tableW.value = percentage + "%";
  console.log(tableW.value);
  updateHeight();
  window.addEventListener("resize", updateHeight);

  // Cleanup listener on component unmount
  return () => {
    window.removeEventListener("resize", updateHeight);
  };
});
function createData(arr: any) {
  const colList: any = [
    {
      title: "OPX",
      key: "station",
      width: 120,
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
    {
      title: "任务",
      key: "task",
      width: 120,
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
    {
      title: "产品名称",
      width: 120,
      key: "productName",
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
  ];

  const list: any = [];
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    const plan = element.produceTask.plan;
    const completed = element.produceTask.completed;
    const Qualified = element.produceTask.qualified;
    const Defective = element.produceTask.defective;
    const planData: any = {
      key: list.length,
      station: element.station,
      productName: element.productName,
    };
    let unit = "";
    if (params.value.type === "天") {
      unit = "午";
    } else if (params.value.type === "月") {
      unit = "半月";
    } else {
      unit = "半年";
    }
    for (let k = 0; k < plan.length; k++) {
      const task = plan[k];
      const findIndex = colList.findIndex((e: any) => e.title === task.time);
      if (findIndex === -1) {
        colList.push({
          title: task.time,
          key: "time",
          algin: "center",
          titleAlign: "center",
          width: 140,
          children: [
            {
              title: "上" + unit,
              key: [task.time + "firstHalf"],
              algin: "center",
              titleAlign: "center",
            },
            {
              title: "下" + unit,
              key: [task.time + "secondHalf"],
              algin: "center",
              titleAlign: "center",
            },
          ],
        });
      }
      planData.task = "计划中";
      planData[task.time + "firstHalf"] = task.firstHalf;
      planData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(planData);
    const completedData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < completed.length; k++) {
      const task = completed[k];
      completedData.task = "已完成";
      completedData[task.time + "firstHalf"] = task.firstHalf;
      completedData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(completedData);
    const QualifiedData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < Qualified.length; k++) {
      const task = Qualified[k];
      QualifiedData.task = "已完成合格品";
      QualifiedData[task.time + "firstHalf"] = task.firstHalf;
      QualifiedData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(QualifiedData);
    const DefectiveData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < Defective.length; k++) {
      const task = Defective[k];
      DefectiveData.task = "已完成瑕疵品";
      DefectiveData[task.time + "firstHalf"] = task.firstHalf;
      DefectiveData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(DefectiveData);
  }
  data.value = list;
  scrollX.value = colList.length * 140 - 180;
  columns.value = colList;
}
async function downloadXLSX(url: string) {
  console.log(url);
  let fileName = url.slice(url.lastIndexOf("/") + 1); // 这里是通过从后端获取到的 url  地址中截出来原本的文件名
  const link = document.createElement("a");
  link.href = url;
  // 下载文件的名称及文件类型后缀
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  //在资源下载完成后 清除 占用的缓存资源
  window.URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
}
</script>

<style lang="less" scoped>
.a3-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #ffffff;
  overflow: hidden;

  .tool-view {
    position: relative;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #e3e3e3;
    backdrop-filter: blur(32px);
    padding: 0.3rem 0;

    .tool-l {
      display: flex;
      align-items: center;
      flex: 1;
      .select {
        padding: 0.3rem;
        border: none;
      }
      .pcker-view {
        position: relative;
        .mask {
          position: absolute;
          z-index: 1;
          width: 100%;
          height: 100%;
        }
      }

      span {
        font-size: 0.75rem;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #1c262d;
        margin: 0 0 0 1rem;
      }
    }
    .btn {
      width: 4rem;
      height: 1.6rem;
      font-size: 0.725rem;
    }
    .tool-r {
      padding-right: 30px;
    }
  }

  .table-view {
    height: calc(100vh - 4.8rem);
  }
}
:deep(.n-date-panel) {
  transform: scale(0.8);
  transform-origin: top left;
}
:deep(.n-data-table-td) {
  text-align: center;
}
</style>
